package com.xz.simplerpc.registry;

import com.xz.simplerpc.constants.Constants;
import com.xz.simplerpc.extension.ExtensionLoader;
import com.xz.simplerpc.extension.URL;
import com.xz.simplerpc.rpc.api.*;
import com.xz.simplerpc.utils.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fingal on 2018/1/9.
 */
public class RegistryDirectory<T> implements NotifyListener, Directory<T> {
    private static final Logger logger = LoggerFactory.getLogger(RegistryDirectory.class);

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
    private List<URL> providerUrls;
    private Registry registry;
    private Class<T> serviceType;
    private URL url;

    public RegistryDirectory(Class<T> serviceType, URL url) {
        this.serviceType = serviceType;
        this.url = url;
    }

    public Registry getRegistry() {
        return registry;
    }

    public void setRegistry(Registry registry) {
        this.registry = registry;
    }

    public List<URL> getProviderUrls() {
        return providerUrls;
    }

    public void setProviderUrls(List<URL> providerUrls) {
        this.providerUrls = providerUrls;
    }

    public void subscribe(URL url) {
        registry.subscribe(url, this);
    }

    @Override
    public void notify(List<URL> urls) {
        providerUrls = urls;
        logger.info("..................notify ....................");
    }

    @Override
    public Class getInterface() {
        return null;
    }

    @Override
    public List<Invoker<T>> list(Invocation invocation) throws RpcException {
        List<Invoker<T>> invokers = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(providerUrls)) {
            for(URL url : providerUrls) {
                boolean enabled = true;
                if (url.hasParameter(Constants.DISABLED_KEY)) {
                    enabled = ! url.getParameter(Constants.DISABLED_KEY, false);
                } else {
                    enabled = url.getParameter(Constants.ENABLED_KEY, true);
                }
                if(enabled) {
                    invokers.add(protocol.refer(serviceType, url));
                }
            }
        }
        return invokers;
    }


    @Override
    public URL getUrl() {
        return null;
    }

    @Override
    public boolean isAvailable() {
        return false;
    }

    @Override
    public void destroy() {

    }
}
